import express from 'express'
import cors from 'cors'
import { json } from 'body-parser'
import routes from './routes'
import { logger } from './services/logger'

const app = express()

// CORS 配置
app.use(cors({
    origin: ['http://localhost:5173', 'http://127.0.0.1:5173'],
    credentials: true,
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: ['Content-Type', 'Authorization']
}))

// 解析 JSON
app.use(json())

// 请求日志
app.use((req, res, next) => {
    logger.info(`${req.method} ${req.url}`, {
        body: req.body,
        query: req.query,
        ip: req.ip
    })
    next()
})

// 路由前缀
app.use('/api', routes)

// 错误处理
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
    logger.error('Unhandled error:', err)
    res.status(500).json({ error: '服务器内部错误' })
})

export default app 